home *** CD-ROM | disk | FTP | other *** search
/ Windows News 2010 Summer - Disc 1 / WN_Ete2010_CD1.iso / Onglet5 / Weezo / Weezo setup.exe / {code_appDir} / www / security.php < prev    next >
PHP Script  |  2010-05-19  |  19KB  |  418 lines

  1. <?php
  2. /**
  3.  * Control access to scripts
  4.  *
  5.  * This script is automatically prepend to scripts (php.ini)
  6.  * Verify before each script execution that user is allowed,
  7.  * start session and include commonFunctions.php
  8.  *
  9.  * @category   NA
  10.  * @package    NA
  11.  * @author     Nicolas Bruley / Peer 2 World <contact@weezo.net>
  12.  * @copyright  2005-2009 Nicolas Bruley / Peer 2 World
  13.  * @license    http://www.php.net/license/3_0.txt  PHP License 3.0
  14.  * @version    CVS: $Id:$
  15.  * @link       http://www.weezo.net
  16.  * @since      File available since Release 1.0.0
  17.  */
  18.  
  19. define('DOCUMENTROOT_DIR',str_replace('\\','/',dirname(__FILE__)).'/');
  20. define('INCLUDE_DIR',DOCUMENTROOT_DIR.'includes/');
  21. define('W_THEMES_DIR',DOCUMENTROOT_DIR.'themes/');
  22.  
  23.  
  24. /**
  25.  * @desc Trace incoming connections
  26.  *
  27.  */
  28. function securityDebugRequest(){
  29.     return;
  30.     //if(!isset($_SERVER['REQUEST_URI']) || cfCmpLeft($_SERVER['REQUEST_URI'],'/ping.php')) return ;
  31.     //cfDbg($_SERVER['REQUEST_URI']);
  32.     //cfDebugSetBuffer('sync',array('REMOTE IP'=>@$_SERVER['REMOTE_ADDR'])+getallheaders()+$_POST);
  33.     //cfDebugSingle($_SERVER['REQUEST_URI']);
  34.     //cfDbg(((isset($_SERVER['SERVER_NAME']))?'HTTP-':'CLI-').$_SERVER['REQUEST_URI'],cfAppDocRoot().'/debug.txt');
  35.     //if($_SERVER['REMOTE_ADDR']!=='127.0.0.1') cfDbg($_SERVER['HTTP_USER_AGENT']);
  36. }
  37.  
  38. // Start profiling chrono
  39. $_ENV['chrono'][0]=array('label'=>'Start','time'=>microtime(true));
  40. $_ENV['configurationEnvironment']='browser';
  41. $_ENV['requestID']=rand();
  42.  
  43. // Treeview class autoload
  44. if(substr($_SERVER['PHP_SELF'],0,9)!='/res/misc' && substr($_SERVER['PHP_SELF'],0,7)!='/alias.' && substr($_SERVER['PHP_SELF'],0,4)!='/pub'){
  45.     function __autoload($class_name) {if($class_name=='treeView' || $class_name=='treeViewFolder')  require_once(INCLUDE_DIR.'treeViewClass.php');}
  46. }
  47.  
  48. // Exception extended class
  49. class SecurityException extends Exception {
  50.     public function __toString() {echo "<pre>Exception: '".$this->getMessage()."' in ".$this->getFile().":".$this->getLine()."\nStack trace:\n".$this->getTraceAsString().'</pre>';return'';}
  51. }
  52.  
  53. /**
  54.  ***************************************************************************************************************************
  55.  * Dump PHP errors into /data/log/phpErrors.txt
  56.  ***************************************************************************************************************************
  57.  */
  58. function securityErrorHandler($errno, $errstr, $errfile, $errline){
  59.     static $cache;
  60.     if (error_reporting() == 0) return true; // No err report for @ prefixed functions
  61.  
  62.     // If errors must be logged
  63.     if ((error_reporting() | $errno) == error_reporting() && cfGGetVar('phpLogErrors')) {
  64.         $errorType = array (E_ERROR=>'ERROR',E_WARNING=>'WARNING',E_PARSE=>'PARSINGERROR',E_NOTICE=>'NOTICE',E_CORE_ERROR=>'COREERROR',E_CORE_WARNING=>'COREWARNING',E_COMPILE_ERROR=>'COMPILEERROR',E_COMPILE_WARNING=>'COMPILEWARNING',E_USER_ERROR=>'USERERROR',E_USER_WARNING=>'USERWARNING',E_USER_NOTICE=>'USERNOTICE',E_STRICT=>'STRICTNOTICE',E_RECOVERABLE_ERROR=>'RECOVERABLEERROR');
  65.         if (array_key_exists($errno, $errorType)) $err = $errorType[$errno]; else $err = 'CAUGHT EXCEPTION';
  66.         cfAppendTextToFile(date('d/m, H:i:s').':'."$err [$errno] $errstr in $errfile on line $errline",cfAppDataDir().'/log/phpErrors.txt');
  67.     }
  68.     if(!isset($cache)) $cache=(bool)cfGGetVar('phpHideErrors');
  69.     // If errors must be displayed
  70.     return $cache;
  71. }
  72.  
  73. /**
  74.  * @desc write log event, display error page if needed and exit() so called script is not executed
  75.  *
  76.  * @param string $logString : log text
  77.  * @param intenger $logLevel
  78. */
  79. function securityRejectConnection($logString=false, $logLevel=LOG_DBG){
  80.     if($logString) cfLog('security.php:'.$logString ,$logLevel);
  81.  
  82.     // Normal GET/POST request
  83.     if(!isset($_GET['asyncRequest'])  && !isset($_POST['asyncRequest'])){
  84.         
  85.         // Published resource: weezo session has expired due to use inactivity, but publish token is still in cookie: re-log.
  86.         if(isset($_COOKIE['weezoPublishToken']))    {
  87.             $_ENV['publishTokenBeforeLogoutURI']=$_SERVER['REQUEST_URI'];
  88.             require_once(cfAppDocRoot().'/login.php');
  89.         }
  90.         else if($_SERVER['PHP_SELF']=='/index.php') {
  91.             $securityEvent=$logString;
  92.             require_once(cfAppDocRoot().'/login.php');
  93.         }
  94.         else{
  95.             // Insert script for reloading page after 2secs in highest possible frame
  96.             $logString.='<script language="javascript" type="text/javascript">function reloadIndex(){';
  97.             $logString.='var l,f=window; while(1){try{if(f.parent && f!=f.parent && f.parent.location) f=f.parent; else break;} catch(e){break}}';
  98.             $logString.='f.location="/index.php"}';
  99.             $logString.='W.setTimeout("reloadIndex()",2000);';
  100.             $logString.='</script>';
  101.  
  102.             require_once(INCLUDE_DIR.'outputFunctions.php');
  103.             outDisplayErrorPage($logString);
  104.         }
  105.     }
  106.     // Async request
  107.     else{
  108.         cfAsyncHeader();
  109.         echo cfAsyncXMLJSaction('document.location.reload()').cfAsyncFooter();
  110.     }
  111.     exit();
  112. }
  113.  
  114. /**
  115.  * Preprocess POST & GET
  116.  *
  117.  */
  118. function securityPreprocessArgs(){
  119.     // Transforms command-line args into GET args
  120.     if(isset($_SERVER['argv'])) {foreach ($_SERVER['argv'] as $expr) if(strpos($expr,'=')) $_GET[substr($expr,0,strpos($expr,'='))]=substr($expr,strpos($expr,'=')+1);}
  121.     // Transform async GET request into POST (backward compatibility)
  122.     if(isset($_GET['asyncRequest']) && $_GET['asyncRequest']==true) $_POST=$_GET;
  123.     // Correct POST parameters sent by HTTPXmlRequest
  124.     if(isset($_POST['asyncRequest']) && $_POST['asyncRequest']=='true'){
  125.         foreach ($_POST as $key=>$value) $_POST[$key]=str_replace('$weezoPlus$','+', $_POST[$key]);
  126.     }
  127.     // Correct GET parameters
  128.     else foreach ($_GET as $key=>$value) $_GET[$key]=str_replace('$weezoPlus$','+', $_GET[$key]);
  129.  
  130.     // Convert $_GET['reloadPostData'] into actual $_POST data
  131.     if(isset($_POST['reloadPostData']) && $_POST['reloadPostData']) {
  132.         foreach (explode('&',$_POST['reloadPostData']) as $d) {
  133.             list($k,$v)=explode('=',$d,2); $_POST[$k]=base64_decode($v);
  134.         }
  135.     }
  136. }
  137.  
  138. /**
  139.  ***************************************************************************************************************************
  140.  * Script access control function
  141.  ***************************************************************************************************************************
  142.  */
  143. function securityResourceVerifyAccessRight(){
  144.     global $w_lng;
  145.  
  146.     $exeptionsListBeforeSessionStart=array(
  147.     '/dummy.php',
  148.     '/404.php',
  149.     '/UWA.php',
  150.     '/index.php',
  151.     '/login.php',
  152.     '/ping.php',
  153.     '/forbidden.php',
  154.     '/ext/video.php',
  155.     '/ext/videoIPhone.php',
  156.     '/ext/image.php',
  157.     '/ext/audio.php',
  158.     '/ext/download.php',
  159.     '/ext/publishedVideo.php',
  160.     '/bittorrentSeeder.php',
  161.     '/bittorrentTracker.php',
  162.     '/widgets/monitor.php',
  163.     '/servDbg.php',
  164.     '/local/tmp.php'
  165.     );
  166.     $exeptionsListBeforeLogin=array(
  167.     '/themes/themePreview.php',
  168.     '/themes/themePreviewMenu.php',
  169.     '/themes/themePreviewBody.php',
  170.     '/help.php'
  171.     );
  172.     $exeptionsListAfterLogin=array(
  173.     '/menuFrame.php',
  174.     '/mainFrame.php',
  175.     '/noResource.php',
  176.     '/imgGen.php',
  177.     '/themes/wallpaperSelection.php',
  178.     '/ext/flvVolume.php'
  179.     );
  180.  
  181.     // Block weezo proxy
  182.     if(isset($_SERVER['HTTP_USER_AGENT']) && substr($_SERVER['HTTP_USER_AGENT'],-10)=='weezoProxy') die(cfCaption('genNoAccess'));
  183.  
  184.     // Disable controls for CLI scripts
  185.     if(cfIsCLI())  return true;
  186.  
  187.     // Disable control for IU scripts
  188.     if(substr($_SERVER['PHP_SELF'],0,5)=='/tmp_') return true;
  189.  
  190.     // Disable control for CSS
  191.     if(substr($_SERVER['PHP_SELF'],-4)=='.css')  return true;
  192.  
  193.     // Disable controls for tests and scripts located in pub folder
  194.     if(substr($_SERVER['PHP_SELF'],0,5)=='/test' || substr($_SERVER['PHP_SELF'],0,5)=='/pub/' || substr($_SERVER['PHP_SELF'],0,5)=='/incl') return true;
  195.  
  196.     // Allow 1st server initialization
  197.     if($_SERVER['PHP_SELF']=='/local/serverManagement.php' && isset($_GET['setWeezoKey'])){if(!customIssetKey()) return true;die('invalid key');}
  198.  
  199.     // IE token login workaround (cookie sometimes not set by login process)
  200.     if(isset($_GET['WSESSID']) && !isset($_COOKIE['WSESSID'])) $_COOKIE['WSESSID']=$_GET['WSESSID'];
  201.  
  202.     // If script belongs to exeptionsListBeforeSessionStart (scripts that doesn't need external authentication), authorize
  203.     if(in_array($_SERVER['PHP_SELF'], $exeptionsListBeforeSessionStart)||(substr($_SERVER['PHP_SELF'],0,18)=='/local/logOutputs/')) return true;
  204.  
  205.     // Start session
  206.     wSession_start();
  207.  
  208.     // Flash player upload workaround (WSESSID cookie not sent).
  209.     if(!count($_SESSION)){
  210.         if(isset($_POST['WSESSID']) && file_exists(cfAppDataDir().'/sessiondata/sess_'.$_POST['WSESSID'])) $wSessId=$_POST['WSESSID'];
  211.         elseif(isset($_GET['WSESSID']) && file_exists(cfAppDataDir().'/sessiondata/sess_'.$_GET['WSESSID'])) $wSessId=$_GET['WSESSID'];
  212.         if(isset($wSessId)){
  213.             wSession_write_close();
  214.             wSession_id($wSessId);
  215.             wSession_start();
  216.         }
  217.     }
  218.  
  219.  
  220.     // If script belongs to exeptionList (scripts that doesn't need external authentication (but need session start)), authorize
  221.     if(in_array($_SERVER['PHP_SELF'], $exeptionsListBeforeLogin)) return true;
  222.  
  223.     // Restore get parameters stored in session (used for transporting authentication data for third-party config scripts)
  224.     if(cfGGetVar('resourceConfigOriginalGET')) {
  225.         parse_str(cfGGetVar('resourceConfigOriginalGET'),$get);
  226.         $_GET+=$get;
  227.     }
  228.  
  229.     // Exeption for script launched by UI
  230.     $weezoKey=(isset($_GET['weezoKey']))?$_GET['weezoKey']:((isset($_SESSION['weezoKey']))?$_SESSION['weezoKey']:0);
  231.     while ($weezoKey && !customIssetKey()) usleep(1000);
  232.     if($weezoKey && $_SERVER['REMOTE_ADDR']=='127.0.0.1' && customCheckKey($weezoKey)){
  233.         $_SESSION['weezoKey']=$weezoKey;
  234.         cfGSetVar('configurationEnvironment','application');
  235.         cfGSetVar('resourceConfigScript','1'); // Backward compatibility for phpMyAdmin
  236.         $_ENV['configurationEnvironment']='application';
  237.         return true;
  238.     }
  239.  
  240.     // if not "userLogged" (means that user didn't log in), go to index.php (this should happend when a session expires)
  241.     if (!isset($_SESSION['userLogged'])) securityRejectConnection($_SERVER['PHP_SELF'].' redirected to login (unauthorized access or session expired)');
  242.  
  243.     // if session IP adress doesn't match with remote adress, go to login page
  244.     if (!isset($_SESSION['userId']) || ($_SESSION['accountIP'] != $_SERVER['REMOTE_ADDR'] && cfGGetVar('disableClientSessionIPControl')!=true && !isset($_SERVER['HTTPS']))) {
  245.         if($_SERVER['PHP_SELF']=='/index.php') unset($_SESSION);
  246.         securityRejectConnection('Redirected to login (unauthorized access : IP doesnt match with session ID)');
  247.     }
  248.  
  249.     // If script belongs to exeptionsListAfterLogin (scripts that need external authentication but that are not resources), authorize
  250.     if(in_array($_SERVER['PHP_SELF'], $exeptionsListAfterLogin)) return true;
  251.  
  252.  
  253.     /**
  254.      * Ressource scripts only below this point
  255.      */
  256.     $_ENV['isResource']=1;
  257.  
  258.     // If script is not located within /res/ directories, refuse connection
  259.     if(substr($_SERVER['PHP_SELF'],0,5)!='/res/') {
  260.         // Check for website/html resources
  261.         if(substr($_SERVER['REQUEST_URI'],0,7)!='/alias.') securityRejectConnection('Unauthorized script access');
  262.         $alias=substr($_SERVER['REQUEST_URI'],1); $alias=substr($alias,0,strpos($alias,'/'));
  263.         foreach ($_SESSION['res'] as $k=>$v) if(@$v['type']=='website' && @$v['subType']=='html'){
  264.             $resData=cfMGetVar('weezoResData'.@$v['id']);
  265.             // Matching resource found: write_close weezo session and proceed
  266.             if($alias==@$resData['alias']){
  267.                 cfPingUpdate();
  268.                 wSession_write_close();
  269.                 unset($resData);unset($_SESSION);
  270.                 return true;
  271.             }
  272.         }
  273.         securityRejectConnection('Unauthorized script access');
  274.     }
  275.  
  276.     // Exception: configuration script
  277.     if(cfCmpLeft($_SERVER['PHP_SELF'],'/res/administration/config')) return true;
  278.  
  279.     // Check if resource Id (resId) has been transmitted
  280.     if(isset($_GET ['resId'])&& is_numeric($_GET ['resId']) && isset($_SESSION['res'][$_GET ['resId']]) && is_array($_SESSION['res'][$_GET ['resId']])) $resId=$_GET ['resId'];
  281.     if(isset($_POST['resId'])&& is_numeric($_POST['resId']) && isset($_SESSION['res'][$_POST['resId']]) && is_array($_SESSION['res'][$_POST['resId']])) $resId=$_POST['resId'];
  282.  
  283.     // resource id provided
  284.     if(isset($resId)){
  285.         if(substr($_SERVER['PHP_SELF'],0,strlen('/res/'.$_SESSION['res'][$resId]['type'].'/'.$_SESSION['res'][$resId]['subType']))=='/res/'.$_SESSION['res'][$resId]['type'].'/'.$_SESSION['res'][$resId]['subType']){
  286.             $_SESSION['activeResourceId']=$resId;// set activeResourceId
  287.  
  288.             // Log first connection
  289.             if(!cfRGetVar('resFirstSelection')) {
  290.                 cfLog(cfUTF8Decode(cfCaption('logResourceSelection',cfUTF8Encode(cfRGetVar('name')),false,false,true)),LOG_DET);
  291.                 cfLogEvent(cfCaption('logResourceSelection',cfUTF8Encode(cfRGetVar('name')),false,false,true).' ('.cfUTF8Encode(cfUGetVar('name')).')',EVENT_RESOURCEACCESS,0,cfUGetVar('id').'/'.cfRGetVar('id'));
  292.                 cfRSetVar('resFirstSelection',true);
  293.             }
  294.             // Log information in statistics database
  295.             if(cfGGetVar('logUserActivity') && !isset($_POST['noSt']) && !isset($_POST['asyncRequest'])) {
  296.                 require_once(INCLUDE_DIR.'databaseFunctions.php');
  297.                 dbLogResourceAccess();
  298.             }
  299.             cfPingUpdate(); // Ping app if no ping since a too long time
  300.             return true;
  301.         }
  302.         else {//resource doesn't exist, load standard login page
  303.             securityRejectConnection('Redirected to login (unauthorized access : require access to unauthorized resource)');
  304.         }
  305.     }
  306.     // if no resource id is received, verify that one of the user's resources matches
  307.     else{
  308.         // 1st verify if active resource matches
  309.         $resourceDir="/res/".cfRGetVar('type')."/".cfRGetVar('subType');
  310.         if(substr($_SERVER['PHP_SELF'],0,strlen($resourceDir))==$resourceDir) {
  311.  
  312.             // Log information in statistics database
  313.             if(cfGGetVar('logUserActivity') && !isset($_POST['noSt']) && !isset($_POST['asyncRequest'])){
  314.                 require_once(INCLUDE_DIR.'databaseFunctions.php');
  315.                 dbLogResourceAccess();
  316.             }
  317.             cfPingUpdate(); // Ping app if no ping since a too long time
  318.             return true;
  319.         }
  320.         //if activeResourceId doesn't match, checks all the other user's resources
  321.         for ($i=0;$i<count($_SESSION['res']);$i++){
  322.             $resourceDir = "/res/".$_SESSION['res'][$i]['type']."/".$_SESSION['res'][$i]['subType'];
  323.             if(substr($_SERVER['PHP_SELF'],0,strlen($resourceDir))==$resourceDir){//current resource belongs to authorized resources
  324.                 $_SESSION['activeResourceId']=$i;//set to activeResourceId
  325.                 // WARNING : an error may occure when an user opens 2 windows with 2 different resources of the same type.
  326.                 cfLog('Authorized (on non active resource)',LOG_DBG);
  327.                 // Log information in statistics database
  328.                 if(cfGGetVar('logUserActivity') && !isset($_POST['noSt']) && !isset($_POST['asyncRequest'])){
  329.                     require_once(INCLUDE_DIR.'databaseFunctions.php');
  330.                     dbLogResourceAccess();
  331.                 }
  332.                 cfPingUpdate(); // Ping app if no ping since a too long time
  333.  
  334.                 return true;
  335.             }
  336.         }
  337.     }
  338.     securityRejectConnection('Access control unsuccessfull');
  339. }
  340.  
  341. // Include common functions
  342. require(INCLUDE_DIR.'commonFunctions.php');
  343. set_error_handler('securityErrorHandler');
  344.  
  345.  
  346.  
  347. // Trace incoming requests
  348. securityDebugRequest();
  349.  
  350. // Preprocess POST & GET
  351. securityPreprocessArgs();
  352.  
  353. /*****************************************************************************************
  354.  * Server initialization
  355.  *****************************************************************************************/
  356.  
  357. // Wait until server initalization complete (done by another thread)
  358. while(cfMIssetVar('weezoInitInProgress')) usleep(10000);
  359.  
  360. // Load general.ini parameters (should happend only once per server launch), except for CLI scripts, and reset sessions files
  361. if((!cfMIssetVar('weezoGeneral')) && isset($_SERVER['SERVER_NAME']) && $_SERVER['REQUEST_URI']!='/local/tmp.php') {require_once(INCLUDE_DIR.'initFunctions.php');    ifInitializeServer();}
  362.  
  363. // Store those parameters into an $_ENV array for faster access
  364. elseif(isset($_SERVER['SERVER_NAME'])) $_ENV['weezoGeneral']=cfMGetVar('weezoGeneral');
  365.  
  366. // If UI embeded script, force session id to sess_UI_+weezoKey
  367. if(isset($_GET['weezoKey']) && $_SERVER['REMOTE_ADDR']=='127.0.0.1' && !cfIsCLI()){
  368.     while (!customIssetKey() && !isset($_GET['setWeezoKey'])) usleep(1000);
  369.     if(customCheckKey($_GET['weezoKey'])) wSession_id('UI_'.$_GET['weezoKey']);
  370. }
  371.  
  372.  
  373. /*****************************************************************************************
  374.  * Verify access rights
  375.  *****************************************************************************************/
  376. securityResourceVerifyAccessRight();
  377.  
  378. /*****************************************************************************************
  379.  * Post-processing: extensions session management
  380.  *****************************************************************************************/
  381.  
  382. // CSS / HTML: send correct headers
  383. if(substr($_SERVER['PHP_SELF'],-4)=='.css'||substr($_SERVER['PHP_SELF'],-5)=='.html'||substr($_SERVER['PHP_SELF'],-4)=='.htm') {
  384.     header('Content-Type: text/'.((substr($_SERVER['PHP_SELF'],-4)=='.css')?'css':'html'));
  385.     WHeaders::cache();
  386.     return;
  387. }
  388.  
  389.  
  390.  
  391. // If resource starts session by itself, close started session
  392. if(isset($_SESSION['activeResourceId'])    && cfRGetVar('definition','resourceStartsSession') && cfIsResource()) {
  393.     wSession_write_close();
  394.     $_ENV['weezoSession']=$_SESSION; $_SESSION=array();
  395. }
  396.  
  397. if($_ENV['configurationEnvironment']=='application'){
  398.  
  399.     // New resource configuration script called: load resource data into $_SESSION so cfRgetVar can be used
  400.     if($_SERVER['SCRIPT_NAME']=='/res/administration/std/resourceConfig.php' && isset($_GET['resourceConfigScript']) && isset($_GET['resourceConfigFilename'])){
  401.         // Resolve resource UID from config filename
  402.         if($id=array_search($_GET['resourceConfigFilename'],cfMGetVar('weezoResourcesList'))){
  403.             // Copy resource data into $_SESSION
  404.             $_SESSION['activeResourceId']=0;
  405.             $_SESSION['res'][0]=cfMGetVar('weezoResData'.$id);
  406.             wSession_write_close();
  407.         }
  408.     }
  409.     // Extensions configuration: if resource config use it's own sessions, put $_SESSION into $_ENV['weezoSession'] so cfRGetVar can work, and close weezo session
  410.     elseif((cfCmpLeft($_SERVER['SCRIPT_NAME'],'/res/misc/') || cfCmpLeft($_SERVER['SCRIPT_NAME'],'/res/administration/phpMyAdmin')) && @$_SESSION['res'][0]['definition']['describer']['configStartsSession']){
  411.         wSession_write_close(false); // Don't save weezo session (as $_SESSION might be altered by resource)
  412.         $_ENV['weezoSession']=$_SESSION;
  413.         $_SESSION=array(); // Reset session data
  414.     }
  415.     // Close session for all other UI scripts
  416.     else wSession_write_close();
  417. }
  418. ?>